package com.gitee.candy.other;

import javax.swing.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author ：suyanlong
 * @date ：Created in 2020/8/6 16:47
 * @description：java打开&关闭浏览器的方式
 * @version: 1.0
 */
public class OpenBrowser {
    public static void main(String[] args) {
        String url = "https://www.baidu.com";

//        urlExists(url);
//        closeBrowse();
//        openIEBrowser(url);
//        openBroser1(url);
//        openBroser2(url);
//        openURL3(url);
    }

    /**
     * @Description: 关闭浏览器（关闭指定的浏览器，在此处是强行关闭浏览器，强行杀死进程）
     * @修改备注:
     */
    public static void closeBrowse() {
        try {
            Runtime.getRuntime().exec("taskkill /F /IM chrome.exe");
            Runtime.getRuntime().exec("taskkill /F /IM iexplorer.exe");
            Runtime.getRuntime().exec("taskkill /F /IM 360se.exe");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void openBroser1(String url) {
        if (java.awt.Desktop.isDesktopSupported()) {
            try {
                // 创建一个URI实例
                java.net.URI uri = java.net.URI.create(url);
                // 获取当前系统桌面扩展
                java.awt.Desktop dp = java.awt.Desktop.getDesktop();
                // 判断系统桌面是否支持要执行的功能
                if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) {
                    // 获取系统默认浏览器打开链接
                    dp.browse(uri);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void openBroser2(String url) {
        try {
            Process process = Runtime.getRuntime().exec(
                    "cmd   /c   start   " + url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void openURL3(String url) {
        try {
            browse(url);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error attempting to launch web browser:\n" + e.getLocalizedMessage());
        }
    }

    /**
     * 判断不同系统打开浏览器
     *
     * @param url
     */
    private static void browse(String url) throws ClassNotFoundException, IllegalAccessException,
            IllegalArgumentException, InterruptedException, InvocationTargetException, IOException,
            NoSuchMethodException {
        String osName = System.getProperty("os.name", "");
        if (osName.startsWith("Mac OS")) {
            Class fileMgr = Class.forName("com.apple.eio.FileManager");
            Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[]{String.class});
            openURL.invoke(null, new Object[]{url});
        } else if (osName.startsWith("Windows")) {
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
        } else { // assume Unix or Linux
            String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
            String browser = null;
            for (int count = 0; count < browsers.length && browser == null; count++)
                if (Runtime.getRuntime().exec(new String[]{"which", browsers[count]}).waitFor() == 0)
                    browser = browsers[count];
            if (browser == null)
                throw new NoSuchMethodException("Could not find web browser");
            else
                Runtime.getRuntime().exec(new String[]{browser, url});
        }
    }

    /**
     * @Description:判断URL指定的页面是否存在
     */
    public static boolean urlExists(String urlStr) {
        try {
            //设置此类是否应该自动执行 HTTP 重定向（响应代码为 3xx 的请求）。
            HttpURLConnection.setFollowRedirects(false);
            //到 URL 所引用的远程对象的连接
            HttpURLConnection con = (HttpURLConnection) new URL(urlStr).openConnection();
            //设置 URL 请求的方法， GET POST HEAD OPTIONS PUT DELETE TRACE 以上方法之一是合法的，具体取决于协议的限制。
            con.setRequestMethod("HEAD");
            //从 HTTP 响应消息获取状态码
            con.connect();
            con.getHeaderFields();
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                System.out.println("****存在");
                return true;
            } else {
                System.out.println("****bu存在");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("****异常");
            return false;
        }
    }

    /**
     * @Description: 使用IE浏览器访问指定URL的页面
     */
    public static void openIEBrowser(String url) {
        //启用cmd运行IE的方式来打开网址。
        try {
            Runtime.getRuntime().exec(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
